using System;
using System.Text.RegularExpressions;
using System.Xml.Serialization;
using System.Xml;
using System.Text;
using System.IO;

namespace ICommonLibrary.Xml {

    public class XmlUtil {

        public static Regex XmlIdentifierRegex = new Regex(@"^[A-Za-z_][A-Za-z_0-9]*$", RegexOptions.CultureInvariant);
        public static readonly string XmlIdentifierRequirement = "A valid identifier must start with a letter followed by underscores, letters or numerals.";

        public static bool IsValidXmlId(string id) {
            return id != null && XmlIdentifierRegex.IsMatch(id);
        }

        public static void ValidateXmlId(string id) {
            if (!IsValidXmlId(id)) {
                throw new ArgumentException(XmlIdentifierRequirement);
            }
        }

        public static string Serialize<T>(T value) where T : class
        {
            if (value == null) return null;

            XmlSerializer xs = new XmlSerializer(typeof(T));
            XmlWriterSettings settings = new XmlWriterSettings()
            {
                Encoding = new UnicodeEncoding(false, false),
                Indent = false,
                OmitXmlDeclaration = false
            };
            using (StringWriter sw = new StringWriter())
            {
                using (XmlWriter xw = XmlWriter.Create(sw, settings))
                {
                    xs.Serialize(xw, value);
                    return sw.ToString();
                }
            }
        }

        public static T Deserialize<T>(string xml) where T : class
        {
            if (string.IsNullOrEmpty(xml))
                return null;

            XmlSerializer serializer = new XmlSerializer(typeof(T));

            XmlReaderSettings settings = new XmlReaderSettings();
            // No settings need modifying here

            using (StringReader textReader = new StringReader(xml))
            {
                using (XmlReader xmlReader = XmlReader.Create(textReader, settings))
                {
                    return (T)serializer.Deserialize(xmlReader);
                }
            }
        }

    }
}